package com.example.demo.Controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.Entity.AdminEntity;
import com.example.demo.Entity.LoginEntity;
import com.example.demo.Entity.ResultEntity;
import com.example.demo.Service.AdminService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin
public class AdminController {
    @Resource
    AdminService adminService;

    @RequestMapping("/login")
    public ResultEntity AdminLogin(@RequestBody LoginEntity data){
        String username = data.getUsername();
        String password = data.getPassword();
        AdminEntity admin;
        admin = adminService.get(username);

        ResultEntity res = new ResultEntity();
        JSONObject json = new JSONObject();

        if(username.equals(admin.getUsername()) && password.equals(admin.getPassword())){
            res.setCode(20000);
            json.put("token","admin-token");
            res.setData(json);
            return res;
        }
        else
            res.setCode(20001);
            return res;
    }

    @RequestMapping("/info")
    public ResultEntity AdminInfo(@RequestParam("token") String token) {
        AdminEntity admin;
        admin = adminService.get(token);
        ResultEntity res = new ResultEntity();
        JSONObject json = new JSONObject();
        ArrayList role = new ArrayList();

        if(token.equals(admin.getToken())){
            res.setCode(20000);
            role.add(admin.getRoles());
            json.put("roles",role);
            json.put("introduction",admin.getIntroduction());
            json.put("avatar",admin.getAvatar());
            json.put("name",admin.getName());
            res.setData(json);
            return res;
        }
        else
            res.setCode(20001);
            return res;
    }

    @RequestMapping("/logout")
    public ResultEntity AminLogout() {
        ResultEntity res = new ResultEntity();
        JSONObject json = new JSONObject();
        res.setCode(20000);
        json.put("data","success");
        res.setData(json);
        return res;
    }
}
